<template id="">
  <div class="OptimalSolution" id="OptimalSolution">
    <el-row :gutter="5">
      <el-col :span="20">
        <div class="grid-content">
          <el-table :data="invoice_list" border show-summary style="border width: 100%" max-height="300" ref="multipleTable" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="56">
            </el-table-column>
            <el-table-column prop="date" label="发票日期" width="115" sortable>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="85" sortable>
            </el-table-column>
            <!-- <el-table-column prop="created" label="添加时间" width="165" sortable> -->
            <!-- </el-table-column> -->
            <el-table-column prop="desc" label="描述" width="164" sortable  >
            </el-table-column>
            <el-table-column label="操作" width="50">
              <template slot-scope="scope">
                <el-button @click.native.prevent="deleteRow(scope.$index, invoice_list)" type="text" size="small">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="4">
        <el-row>
          <el-button style="width:100px" type="primary" @click="openAddInvoiceDialog(null)">添加发票</el-button>
        </el-row>
        <el-row>
          <el-button style="width:100px" type="primary" @click="delSelectInvoices()">删除选中</el-button>
        </el-row>
        <el-row>
          <el-button style="width:100px" type="primary" @click="statInvoice()">汇总求和</el-button>
        </el-row>
        <el-row>
          <el-input style="width:100px" v-model.number="input_target" placeholder="目标金额"></el-input>
        </el-row>
        <el-row>
          <el-button style="width:100px" type="primary" @click="getOptimalSolution()">求&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;解</el-button>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog title="增加发票" :visible.sync="dialogFormVisible" top="10vh">
      <el-form ref="form" :model="form" label-width="50px">
        <el-form-item label="ID:">
          <el-input v-model="form.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="金额:">
          <el-input v-model="form.amount" oninput = "value=value.replace(/[^\d.]/g,'')"></el-input>
           <template slot="append">元</template>
        </el-form-item>
        <el-form-item label="时间:" >
          <el-date-picker type="date" placeholder="选择日期" v-model="form.date" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="描述:" >
          <el-input v-model="form.desc" maxlength="10" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addInvoice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const INVOICE_STORE_KEY = "INVOICE_STORE"
  export default {
    name: 'OptimalSolution',
    data() {
      return {
        form: {
          id: '',
          amount: '',
          date: new Date(),
          desc: ''
        },
        invoice_list: [],
        multipleSelection: [],
        checkboxGroup: [],
        input_target: 0.0,
        dialogFormVisible: false,
      }
    },
    methods: {
      onlyDoubleInput(value){
        console.log(this.form.amount);
        console.log(value);
        this.form.amount=this.form.amount.replace(/[^\d.]/g,'')
      },
      getOptimalSolution(){
        var allInvoice = this.getInvoiceFromStore();
        var invoiceList = [];
        var target = new Object;
        for (var i in this.multipleSelection){
          delete allInvoice[this.multipleSelection[i].id]
        }
        for (var i in allInvoice){
          invoiceList.push(allInvoice[i])
        }
        invoiceList = invoiceList.sort((x, y) => x.amount >= y.amount ? 1 : -1)
        console.log(invoiceList);
        alert('求最优解,target='+this.input_target)
      },
      getInvoiceFromStore(){//从存储中获取发票数据
        var invoices = localStorage.getItem(INVOICE_STORE_KEY);
        invoices = invoices == null ? new Object() : JSON.parse(invoices)
        return invoices
      },
      saveInvoiceAndFlush(invoices){//保存并刷新表格数据
        localStorage.setItem(INVOICE_STORE_KEY, JSON.stringify(invoices))
        this.flushInvoiceList(invoices)
      },
      statInvoice(){
          var invoices = this.getInvoiceFromStore();
          var count=0;
          var sum=0.0;
          for (var i in invoices) {
            count++;
            sum+=invoices[i].amount
          }
          this.$alert('总计: '+count+' 张,总金额: '+sum.toFixed(2)+' 元','发票汇总', {
          confirmButtonText: '确定',
          closeOnPressEscape:true,
          callback: action => {}
        });
      },
      delSelectInvoices(){//批量删除发票
        let invoices = this.getInvoiceFromStore()
        for (var i in this.multipleSelection) {
          delete invoices[this.multipleSelection[i].id]
        }
        this.saveInvoiceAndFlush(invoices)
      },
      handleSelectionChange(val) {//处理选中事件,用来获被选中的对象
        this.multipleSelection = val;
      },
      deleteRow(index, rows) {//单行删除
        var invoices = this.getInvoiceFromStore()
        delete invoices[rows[index].id]
        this.saveInvoiceAndFlush(invoices)
      },
      openAddInvoiceDialog(type) {//打开增加发票对话框
        this.dialogFormVisible = true;
        if (type == null) {
          this.form.id = this.createRandomId()
        }
      },
      addInvoice() {//增加发票
        this.dialogFormVisible = false;
        var newInvoice = new Object;
        newInvoice['id'] = this.form.id;
        newInvoice['amount'] = parseFloat(this.form.amount);
        newInvoice['date'] = this.form.date.format('yyyy/MM/dd');
        newInvoice['desc'] = this.form.desc;
        newInvoice['created'] = new Date().format("yyyy/MM/dd hh:mm:ss");
        var invoices =  this.getInvoiceFromStore()
        invoices[newInvoice['id']] = newInvoice
        this.saveInvoiceAndFlush(invoices)
      },
      createRandomId() {//创建唯一的随机 ID
        return (Math.random() * 10000000).toString(16).substr(0, 4) + '-' + (new Date()).getTime() + '-' + Math.random().toString().substr(2, 5);
      },
      flushInvoiceList(invoicesMap) {//刷新表格
        let invoices = []
        for (var key in invoicesMap) {
          invoices.push(invoicesMap[key])
        }
        this.invoice_list = invoices.sort((x, y) => x.date >= y.date ? 1 : -1)
      }
    },
    created() {
      var invoices = this.getInvoiceFromStore()
      this.flushInvoiceList(invoices)
    }
  }
</script>

<style scoped>
.el-dialog .el-form-item{
    margin-top: 5px;
    margin-bottom: 5px;
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .el-row {
    margin-bottom: 20px;
  }

  .el-col {
    border-radius: 4px;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
</style>
